package servlet;

import util.DBUtils;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author LJ
 * @create 2022-04-21-16:36
 */
@WebServlet("/loginG")
public class loginG extends HttpServlet {
    @Override
    public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie[] cookies = req.getCookies();
        String username="";
        String password="";
        if (cookies != null) {

            for (int i = 0; i < cookies.length; i++) {

                System.out.println("cookies[i]"+cookies[i].getName());
                if (cookies[i].getName().equals("username")){
                    username=cookies[i].getValue();
                    System.out.println("username:"+username);
                }else
                if (cookies[i].getName().equals("password")){
                    password=cookies[i].getValue();
                }
                System.out.println("null?"+username);
                System.out.println(password);
                if (!username.equals("") && !password.equals("")){
                    try {
                        System.out.println("ok");
                        Connection connection = DBUtils.getConnection();
                        PreparedStatement preparedStatement = connection.prepareStatement("SELECT username,`password` FROM `sys_user` WHERE username=? and `password`=?");
                        preparedStatement.setString(1, username);
                        preparedStatement.setString(2, password);
                        ResultSet resultSet = preparedStatement.executeQuery();
                        System.out.println("ok");
                        if (resultSet.next()){
                            System.out.println("cookie:"+resultSet.getString("username"));
                            System.out.println("cookie:"+resultSet.getString("password"));
                            resp.sendRedirect("/TestServlet/goMain");
                        }else {
                            resp.sendRedirect("/TestServlet/login.html");
                        }
                    } catch (SQLException throwables) {
                        throwables.printStackTrace();
                    }
                }
            }
        }else {
            System.out.println("真棒");
            resp.sendRedirect("/TestServlet/login.html");
//            RequestDispatcher requestDispatcher = req.getRequestDispatcher("/TestServlet/login");
//            requestDispatcher.forward(req, resp);

        }

    }
}
